#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:department_dao.py
# author:张世航
# datetime:2024/12/20 23:57
# software: PyCharm
"""
this is function  description 
"""
# import module your need


# dao/department_dao.py
import pymysql
from config.config import DATABASE_CONFIG
from models.department import Department

def connect_db():
    """连接数据库"""
    try:
        connection = pymysql.connect(**DATABASE_CONFIG)
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to database: {e}")
        return None

def add_department(department):
    """添加院系信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO department (pid, name) VALUES (%s, %s)"
                cursor.execute(sql, (department.pid, department.name))
                connection.commit()
                print("Department added successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error adding department: {e}")
        finally:
            connection.close()

def delete_department(id):
    """根据院系ID删除信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "DELETE FROM department WHERE id = %s"
                cursor.execute(sql, (id,))
                connection.commit()
                print("Department deleted successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error deleting department: {e}")
        finally:
            connection.close()

def query_department_by_name(name):
    """根据院系名称查询信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * FROM department WHERE name = %s"
                cursor.execute(sql, (name,))
                results = cursor.fetchall()
                for row in results:
                    print(row)
        except pymysql.MySQLError as e:
            print(f"Error querying department: {e}")
        finally:
            connection.close()